﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.IO;
using System.Windows.Forms;
using Telerik.WinControls.UI;
using SdmxMl.Common;
using SdmxMl.Manager;
using SdmxMl.Structure;

namespace SakeVar
{
    public partial class DlgSasExport :  Telerik.WinControls.UI.RadForm
    {
        private GridCreator gridCreator;

        public DlgSasExport(GridCreator gc)
        {
            InitializeComponent();
            gridCreator = gc;
        }

        private void radButtonGenerate_Click(object sender, EventArgs e)
        {
            bool isForSAS = radRadioButtonSAS.ToggleState == Telerik.WinControls.Enumerations.ToggleState.On;
            StringBuilder sb = new StringBuilder();
            if (radRadioButtonInput.ToggleState == Telerik.WinControls.Enumerations.ToggleState.On)
            {
                DlgDataInput aDlg = new DlgDataInput(gridCreator.GetInputTable(), isForSAS);
                aDlg.ShowDialog();
                if (aDlg.DialogResult != DialogResult.OK)
                    return;

                sb = aDlg.sb;
            }

            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {

                using (new SdmxMl.Helper.CWaitCursor())
                {
                    if (radRadioButtonVarLabel.ToggleState == Telerik.WinControls.Enumerations.ToggleState.On)
                        sb = gridCreator.GetVarLabelExport(radRadioButtonSAS.ToggleState == Telerik.WinControls.Enumerations.ToggleState.On);
                    else if (radRadioButtonCodeFormat.ToggleState == Telerik.WinControls.Enumerations.ToggleState.On)
                    {
                        sb = gridCreator.GetFormatExport(radRadioButtonSAS.ToggleState == Telerik.WinControls.Enumerations.ToggleState.On);
                    }

                    using (StreamWriter sw = new StreamWriter(saveFileDialog.FileName, false, Encoding.Default))
                        sw.Write(sb.ToString());

                    DialogResult dr = MessageBox.Show("The data in the grid was exported successfully. Do you want to open the file?",
                        "Export to SAS / SPSS", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (dr == DialogResult.Yes)
                    {
                        System.Diagnostics.Process.Start(saveFileDialog.FileName);
                    }
                }
            }
        }
    }
}
